import React, { PropTypes } from 'react';
import ReactEChart from './charts/ReactEChart';
import moment from 'moment';

const getConfig = ({ tickData, orderInfo }) => {
  const color = '#6bc1ff';
  const serieData = [];
  tickData.forEach((item) => {
    const tickTime = Number.parseInt(moment(item.timeStamp, 'YYYYMMDDHHmmss').format('x'));
    const price = item.LastPx;
    serieData.push([tickTime, price]);
  });

  // tickData.sort((a,b)=>(a-b));

  let buyPos = [new Date(orderInfo.openTime).getTime(), orderInfo.buyPrice.toFixed(2)];
  let sellPos = [new Date(orderInfo.closeTime).getTime(), orderInfo.sellPrice.toFixed(2)];
  if (orderInfo.tradeType === 'Buy') {

  } else if (orderInfo.tradeType === 'Sell') {
    const tmpPos = sellPos;
    sellPos = buyPos;
    buyPos = tmpPos;
  } else {
    throw new Error(`wrong trade type:${orderInfo.tradeType}`);
  }

  const markData = [{
    name: '买入',
    value: orderInfo.buyPrice,
    coord: buyPos,
    itemStyle: {
      normal: {
        color: 'red',
      },
    },
    label: {
      normal: {
        formatter: value => '买',
      },
    },
  }, {
    name: '卖出',
    value: orderInfo.sellPrice,
    coord: sellPos,
    itemStyle: {
      normal: {
        color: 'green',
      },
    },
    label: {
      normal: {
        formatter: value => '卖',
      },
    },
  },
  ];

  return {
    title: {
      text: orderInfo.symbol,
      left: 'center',
    },
    xAxis: {
      type: 'time',
      splitNumber: 8,
      splitLine: {
        show: true,
        lineStyle: {
          color: '#e6e6e6',
        },
      },
      axisLine: {
        lineStyle: {
          color: '#ccd6eb',
        },
      },
      axisLabel: {
        textStyle: {
          color: '#888',
        },
      },
    },
    yAxis: {
      type: 'value',
      boundaryGap: [0, '10%'],
      splitNumber: 3,
      splitLine: {
        lineStyle: {
          color: '#e6e6e6',
        },
      },
      axisLine: {
        lineStyle: {
          color: '#ccd6eb',
        },
      },
      axisLabel: {
        textStyle: {
          color: '#888',
        },
      },
    },
    tooltip: {
      trigger: 'axis',
    },
    series: [{
      name: '价格',
      type: 'line',
      symbol: 'circle',
      showSymbol: false,
      // sampling: 'average',
      itemStyle: {
        normal: {
          color,
        },
      },
      markPoint: {
        data: markData,
      },
      data: serieData,
    }],
  };
};

const StockChart = (props) => {
  const config = getConfig(props);

  return (
    <div style={{ height: 250 }}>
      {config && <ReactEChart config={config} />}
    </div>
  );
};

StockChart.propTypes = {
  tickData: PropTypes.array,
  orderInfo: PropTypes.object,
};

export default StockChart;
